package com.leyou.sms.listener;

import com.leyou.common.constants.RocketMQConstants;
import com.leyou.common.utils.JsonUtils;
import com.leyou.sms.config.SmsProperties;
import com.leyou.sms.utils.SmsHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

import static com.leyou.common.constants.RocketMQConstants.CONSUMER.SMS_VERIFY_CODE_CONSUMER;
import static com.leyou.common.constants.RocketMQConstants.TAGS.VERIFY_CODE_TAGS;
import static com.leyou.common.constants.RocketMQConstants.TOPIC.SMS_TOPIC_NAME;

/**
 * RocketMQ的监听器
 * 从消息中间件拉取消息，发送短信
*/
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = SMS_VERIFY_CODE_CONSUMER,
        topic = SMS_TOPIC_NAME,
        selectorExpression = VERIFY_CODE_TAGS)
public class SendMessageListener implements RocketMQListener<String> {

    @Autowired
    private SmsHelper smsHelper;
    @Autowired
    private SmsProperties prop;
    /**
     * 接收发送短信的内容
     * @param message json字符串  {"phone":"138757575","code":"1111"}
     */
    @Override
    public void onMessage(String message) {

        log.info("[sms]服务，接收到消息，内容message={}",message);
        Map<String, String> msgMap = JsonUtils.toMap(message, String.class, String.class);
        String phone = msgMap.remove("phone");

//        param的内容格式 {"code":"1111"}
        smsHelper.sendMessage(phone,
                prop.getSignName(),
                prop.getVerifyCodeTemplate(),
                JsonUtils.toString(msgMap));
    }
}
